import { notice } from '@/utils/common.js'
import { insp } from '@/utils/business/constants.js'

export default {
	methods: {
		openBle(){
			let _this = this;
		    uni.openBluetoothAdapter({
		        success(data) {
		            _this.available = true
					_this.searchDevice()
		        },
		        fail: (err) => {
					_this.available = false
		        }
		    })
		},
		searchDevice(){
			let _this = this;
		    uni.startBluetoothDevicesDiscovery({
		        success(data) {
		            _this.onBluetoothDeviceFound();
		        },
		        fail(err) {
		            console.log("fail",err);
		        }
		    })
		},
		onBluetoothDeviceFound(){
		    let _this = this;
		    uni.onBluetoothDeviceFound(function(res){
		        let devices = res.devices;
		        for (var i = 0; i < devices.length; i++) {
					const device = devices[i];
					if(device.name.indexOf('BT') !== -1) {
						_this.sensorList.push({
							name: device.name || "Unknown Device",
							deviceId: device.deviceId,
							rssi: device.RSSI
						})
					}
		        }
		    })
		},
		// 停止搜寻蓝牙设备
		stopBluetoothDevicesDiscovery(){ 
			uni.stopBluetoothDevicesDiscovery({ 
				success(res) {
					console.log('停止搜索蓝牙设备:' + res.errMsg); 
				},
				fail(err) {
					console.log('停止搜索蓝牙设备失败，错误码：' + err.errCode);
				}
			});
		},
		// 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接，设备丢失，连接异常断开等等
		onBLEConnectionStateChange() {
			let _this = this;
			uni.onBLEConnectionStateChange(res => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
				if (!res.connected && _this.connectedDevice) {
					_this.connect(_this.connectedDevice, 'auto')
				}
			})
		},
		connect(device, type) {
			// TODO 校验数据字典是否配置该deviceId
			// notice.toast('该传感器未被允许连接该设备,请联系管理员')
			
			if(type != 'auto') {
				uni.showLoading({
				    title: '正在连接，请稍候'
				});
			}
			let _this = this;
			uni.createBLEConnection({
			    deviceId: device.deviceId,
			    success(res) {
					if(type != 'auto') {
						uni.hideLoading()
						notice.toast('连接成功')
					}
					_this.connectedDevice = device
					uni.setStorageSync("bindSensor", _this.connectedDevice)
					
					if(!type) {
						const eventChannel = _this.getOpenerEventChannel();
						eventChannel.emit('bindSensor', _this.connectedDevice);
						
						uni.navigateBack();
					}
					_this.getBLEDeviceServices()
					// _this.stopBluetoothDevicesDiscovery()
			    },
			    fail(err) {
					console.log(err)
					notice.toast('连接失败')
			    }
			})  
		},
		// 获取蓝牙设备所有服务(service)
		getBLEDeviceServices() {
			let _this = this;
			setTimeout(()=>{
				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: _this.connectedDevice.deviceId,
					success(res) {
						console.log('device services:', res.services)
						// 由于连接的不稳定，此处直接写死
						_this.serviceId = insp.SERVICE_ID;
						_this.getBLEDeviceCharacteristics()
						// res.services.forEach((item)=>{
						// 	if(item.uuid.indexOf(insp.SERVICE_ID) != -1){
						// 		_this.serviceId = item.uuid;
						// 		_this.getBLEDeviceCharacteristics()
						// 	}
						// })
					},
					fail:(err)=>{
						console.log(err)
						_this.connectedDevice = ""
						notice.toast('获取服务失败，请重新连接')
					}
				})
			}, 1000)
		},
		// 获取蓝牙设备某个服务中所有特征值(characteristic)
		getBLEDeviceCharacteristics() {
			let _this = this
			setTimeout(()=>{
				uni.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: _this.connectedDevice.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: _this.serviceId,
					success:(res)=>{
						console.log("res.characteristics:", res.characteristics)
						res.characteristics.forEach((item)=>{
							if(item.properties.notify){
								_this.notifyBLECharacteristicValueChange(item.uuid)
							}
						})
					},
					fail:(err)=>{
						console.log(err)
					}
				})
			}, 1000)
		},
		// 启用低功耗蓝牙设备特征值变化时的notify功能，订阅特征值(注意：必须设备的特征值支持notify或者indicate才可以成功调用)
		notifyBLECharacteristicValueChange(characteristicId){
		    let _this = this; 
		    uni.notifyBLECharacteristicValueChange({
		        deviceId: _this.connectedDevice.deviceId,
		        serviceId: _this.serviceId,
		        characteristicId: characteristicId,
		        state:true,
		        success(res) {
					console.log("notify开启通知成功:", res)
		            _this.onBLECharacteristicValueChange();
		        },
		        fail(err) {
		            console.log('notify开启通知失败:', err);
		        }
		    })
		},
		// 监听低功耗蓝牙设备的特征值变化事件
		onBLECharacteristicValueChange(){
		    let _this = this;
			uni.onBLECharacteristicValueChange(function(res){
			    console.log(`特征值 ${res.characteristicId} 变化：` + _this.ab2hex(res.value).join(''));
				let value = _this.ab2hex(res.value)
				// console.log("获取到的原始数据：", value);
				_this.measuredArr = _this.measuredArr == undefined ? [] : _this.measuredArr
				if(value[2] != '55') { // 过滤掉心跳数据
					_this.measuredArr = _this.measuredArr.concat(value)
				}
				// console.log("获取到的处理数据：", _this.measuredArr);
				// setTimeout(()=>{
				// 	_this.measuredValue = _this.handleResult(value)
				// 	console.log('测量结果:', _this.measuredValue);
				// }, 3000)
			});
		},
		// 读取低功耗蓝牙设备的特征值的二进制数据值(注意：必须设备的特征值支持read才可以成功调用)
		readBLECharacteristicValue(characteristicId) {
			let _this = this; 
			uni.readBLECharacteristicValue({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: _this.connectedDevice.deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: _this.serviceId,
				// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
				characteristicId: characteristicId,
				success(res) {
					_this.onBLECharacteristicValueChange();
				}
			})
		},
		// 向低功耗蓝牙设备特征值中写入二进制数据(注意：必须设备的特征值支持write才可以成功调用)
		writeBLECharacteristicValue(characteristicId, buffer) {
			let _this = this;
			uni.writeBLECharacteristicValue({
				// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
				deviceId: _this.connectedDevice.deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: insp.SERVICE_ID, // _this.serviceId,
				// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
				characteristicId: characteristicId,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					// setTimeout(()=>{
					// 	_this.readBLECharacteristicValue('0000FFF1-0000-1000-8000-00805F9B34FB')
					// }, 1000)
				},
				fail(err) {
					console.log(err)
				}
			})
		},
		// ArrayBuffer转16进制字符串示例
		ab2hex(buffer) {
		    const hexArr = Array.prototype.map.call(
		        new Uint8Array(buffer),
		        function(bit) {
		            return ('00' + bit.toString(16)).slice(-2)
		        }
		    )
		    // return hexArr.join('')
			return hexArr
		},
		// 断开连接
		closeConnect() {
			let _this = this;
			uni.closeBLEConnection({
				deviceId: _this.connectedDevice.deviceId,
				success(res) {
					notice.toast('连接已断开')
					_this.connectedDevice = ''
					uni.removeStorageSync('bindSensor')
					
					var pages = getCurrentPages();
					var prevPage = pages[pages.length - 2]; //上一个页面
					prevPage.$vm.relieveBind();
				}
			})
		},
		// 读取温度
		readTemp() {
			const buffer = new ArrayBuffer(6)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x61)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x00)
			dataView.setUint8(5, 0xE2)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 关闭测温
		closeTemp() {
			const buffer = new ArrayBuffer(6)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x62)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x00)
			dataView.setUint8(5, 0xE2)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取加速度
		readAcceleration() {
			const buffer = new ArrayBuffer(6)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x11)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x00)
			dataView.setUint8(5, 0xA2)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取速度
		readSpeed() {
			const buffer = new ArrayBuffer(6)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x21)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x00)
			dataView.setUint8(5, 0x92)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取位移
		readVibration() {
			const buffer = new ArrayBuffer(6)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x31)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x00)
			dataView.setUint8(5, 0xB2)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取加速度波形
		readAccelerationWave() {
			const buffer = new ArrayBuffer(7)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x14)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x05)
			dataView.setUint8(5, 0x00)
			dataView.setUint8(6, 0xbd)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取速度波形
		readSpeedWave() {
			const buffer = new ArrayBuffer(7)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x24)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x05)
			dataView.setUint8(5, 0x00)
			dataView.setUint8(6, 0xbd)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 读取位移波形
		readVibrationWave() {
			const buffer = new ArrayBuffer(7)
			const dataView = new DataView(buffer)
			dataView.setUint8(0, 0x01)
			dataView.setUint8(1, 0x80)
			dataView.setUint8(2, 0x34)
			dataView.setUint8(3, 0x00)
			dataView.setUint8(4, 0x05)
			dataView.setUint8(5, 0x00)
			dataView.setUint8(6, 0xbd)
			
			this.writeBLECharacteristicValue(insp.CHARACTERISTIC_ID, buffer)
		},
		// 处理点数据
		handleResult(data) {
			console.log("原始瞬时数据：", data)
			let result
			// 温度
			if(data[2] == '61') {
				result = parseInt(data[8], 16) + "." + parseInt(data[9], 16)
				if(data[7] == 'ff') {
					result = -result
				}
				// 关闭测温
				this.closeTemp()
			}
			// 加速度 || 速度
			else if(data[2] == '11' || data[2] == '21') {
				result = parseInt(data[5], 16) + "." + parseInt(data[6], 16) + ""
			}
			// 位移
			else if(data[2] == '31') {
				result = parseInt(data[5] + data[6], 16) + ""
			}
			console.log("传感器读取：", result)
			return result
		},
		// 处理波形数据
		handleWaveResult(data) {
			console.log("原始波形数据：", data)
			// 解析波形数据
			let receive_wave_data = []
			let waveData = data.slice(12)
			for(let i=1; i<waveData.length; i+=2) {
				receive_wave_data.push(parseInt(waveData[i] + waveData[i-1], 16))
			}
			console.log("处理后数据：", receive_wave_data);
			
			// 当前波形类型
			let deal_data_type = data[2]
			// 当前波形长度
			let receive_data_length = parseInt(data[4] + data[3], 16) // data[4] + data[5]*256;
			// 当前波形中值
			let current_deal_mid_value = parseInt(data[6] + data[5], 16) // data[6] + data[7]*256;
			// 当前波形增益
			let current_deal_mult_value = parseInt(data[8] + data[7], 16) // data[8] + data[9]*256;
			
			let rms_data_sum = 0
			let temp_wave_mult_value = 0
			let counter_rms_data = []
			let counter_display_data = []
			let rms_data_resault = 0
			
			// 返回加速度数据
			if(deal_data_type == '14') {
				rms_data_sum = 0
				temp_wave_mult_value = current_deal_mult_value/100000.0
				
				for(let i=0; i<receive_wave_data.length; i++) {
					counter_rms_data[i] = receive_wave_data[i] - current_deal_mid_value
					counter_display_data[i] = counter_rms_data[i] * temp_wave_mult_value
					rms_data_sum += counter_display_data[i]*counter_display_data[i]
				}
				rms_data_resault = parseFloat(rms_data_sum*1.0)
				rms_data_resault = parseFloat(rms_data_resault/receive_data_length)
				rms_data_resault = parseFloat(Math.sqrt(rms_data_resault))
				rms_data_resault = parseFloat(rms_data_resault/0.707).toFixed(1)
			}
			// 返回速度数据
			else if(deal_data_type == '24') {
				rms_data_sum = 0
				temp_wave_mult_value = current_deal_mult_value/10000.0
				
				for(let i=0; i<receive_wave_data.length; i++) {
					counter_rms_data[i] = receive_wave_data[i] - current_deal_mid_value
					counter_display_data[i] = counter_rms_data[i] * temp_wave_mult_value
					rms_data_sum += counter_display_data[i]*counter_display_data[i]
				}
				rms_data_resault = parseFloat(rms_data_sum*1.0)
				rms_data_resault = parseFloat(rms_data_resault/receive_data_length)
				rms_data_resault = parseFloat(Math.sqrt(rms_data_resault))
				rms_data_resault = parseFloat(rms_data_resault/0.707)
				rms_data_resault = parseFloat(rms_data_resault/10).toFixed(1)
			}
			// 返回位移数据
			else if(deal_data_type == '34') {
				rms_data_sum = 0
				temp_wave_mult_value = current_deal_mult_value/1000.0
				
				for(let i=0; i<receive_wave_data.length; i++) {
					counter_rms_data[i] = receive_wave_data[i] - current_deal_mid_value
					counter_display_data[i] = counter_rms_data[i] * temp_wave_mult_value
					rms_data_sum += counter_display_data[i]*counter_display_data[i]
				}
				rms_data_resault = parseFloat(rms_data_sum*1.0)
				rms_data_resault = parseFloat(rms_data_resault/receive_data_length)
				rms_data_resault = parseFloat(Math.sqrt(rms_data_resault))
				rms_data_resault = parseFloat(rms_data_resault*2)
				rms_data_resault = parseFloat(rms_data_resault/0.707) 
				rms_data_resault = parseFloat(rms_data_resault/2)
				rms_data_resault = Math.round(rms_data_resault)
			}
			
			// 数据处理
			counter_display_data.forEach(function(item, index, arr) {
				arr.splice(index, 1, Math.round(item))
			})
			
			// console.log("波形数据：", counter_display_data)
			// console.log("最后结果：", rms_data_resault)
			
			let result = {
				dataList: counter_display_data,
				dataValue: rms_data_resault,
				dataType: deal_data_type == '14' ? 'jsd' : deal_data_type == '24' ? 'sudu' : 'zf'
			}
			console.log("返回数据：", result)
			return result
		}
	}
}